<template>
    <el-upload
        :show-file-list="false"
        :on-change="handleChange"
        :auto-upload="false"
        ref="uploadImg"
        :accept="acceptType"
        action="">
        <el-button size="mini" type="primary">{{ $t('common.uploadImage') }}</el-button>
        <div v-if="tips" slot="tip" class="tips" :class="{'right':rightTips}">{{ tips }}</div>
    </el-upload>
</template>

<script>
export default {
    name: 'upload-image-button',
    props: {
        value: {
            type: String,
            default: '',
        },
        tips: {
            type: String,
            default: '',
        },
        rightTips: {
            type: Boolean,
            default: false,
        },
        // 方法返回Promise对象
        checkSize: {
            type: Function,
            default() {
                return Promise.resolve();
            }
        },
    },
    data() {
        return {
            acceptType: 'image/png,image/gif,image/jpg,image/jpeg,image/bmp,image/webp'
        };
    },
    methods: {
        // 检测上传变化
        handleChange(file) {
            // console.log(file);
            if (file) {
                const upload = this.$refs.uploadImg;
                this.checkSize(file.raw).then(() => {
                    const params = new FormData();
                    params.append('file', file.raw);
                    this.$api.customer.fileUpload(params).then(res => {
                        // console.log(res);
                        const { status, data, error } = res;
                        if ('1' === status && '00000000' === error) {
                            this.$emit('input', data.url);
                        }
                        upload.clearFiles();
                    });
                }).catch(() => {
                    upload.clearFiles();
                });
            }
        },
    },
}
</script>

<style lang="scss" scoped>
.tips {
    font-size: 12px;
    &.right{
        text-align: right;
    }
}
</style>
